package org.infrastructure.redis.core;

import java.nio.charset.Charset;

import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.util.Assert;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.parser.ParserConfig;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.TypeFactory;

public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
	@SuppressWarnings("unused")
	private ObjectMapper objectMapper = new ObjectMapper();
	public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

	private final Class<T> clazz;

	static {
		ParserConfig.getGlobalInstance().setAsmEnable(true);
		//ParserConfig.getGlobalInstance().setAutoTypeSupport(true); 
		//如果遇到反序列化autoType is not support错误，请添加并修改一下包名到bean文件路径
		// ParserConfig.getGlobalInstance().addAccept("com.xxxxx.xxx");
	}

	public FastJsonRedisSerializer(final Class<T> clazz) {
		super();
		this.clazz = clazz;
	}

	@Override
	public byte[] serialize(final T t) throws SerializationException {
		if (t == null) {
			return new byte[0];
		}
		return JSON.toJSONString(t).getBytes(FastJsonRedisSerializer.DEFAULT_CHARSET);
		//return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
	}

	@Override
	public T deserialize(final byte[] bytes) throws SerializationException {
		if (bytes == null || bytes.length <= 0) {
			return null;
		}
		final String str = new String(bytes, FastJsonRedisSerializer.DEFAULT_CHARSET);

		return JSON.parseObject(str, clazz);
	}

	public void setObjectMapper(final ObjectMapper objectMapper) {
		Assert.notNull(objectMapper, "'objectMapper' must not be null");
		this.objectMapper = objectMapper;
	}

	protected JavaType getJavaType(final Class<?> clazz) {
		return TypeFactory.defaultInstance().constructType(clazz);
	}
}